package com.young.android.view;

import java.util.ArrayList;

import com.young.android.R;
import com.young.android.atomoperation.OperResource;
import com.young.android.business.MainBusiness;
import com.young.android.business.ResourceBusi;
import com.young.android.common.BaseActivity;
import com.young.android.common.PubFunction;
import com.young.android.entity.Resource;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class Main extends BaseActivity {
    /** Called when the activity is first created. */
    private static final int FINISH_NOTIFIER = 0;
    private Handler handler;

    int mCount;// RSS资源数
    int[] unreadCount;

    // private static final String GOOGLE_ATOM_API = "http://www.google.com/reader/atom/feed/";

    private ListView mResourceList;
    private ImageButton mQuickEditBtn;
    private ImageButton mQuitQuickEditBtn;
    private ImageButton mRefreshBtn;
    private LinearLayout mAddBtn;
    private LinearLayout mBottomLy;
    private LinearLayout mLoadingLy;
    private ImageView mLoadingImage;
    // private LinearLayout mBottomBtnLy;

    String selName;
    String selUrl;

    @Override
    protected void init() {
        // TODO Auto-generated method stub
        setContentView(R.layout.main);

        SetAllowExitApplication(true);

        MainBusiness.LoadConfig(this);
        MainBusiness.OpenDB(this);

        initView();
        
        // 后台更新
        updateDataBackground();

        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case FINISH_NOTIFIER:
                    handleUpdateFinish();
                    break;
                default:
                    break;
                }
            }

        };
    }

    public void initView(){
        mResourceList = (ListView) findViewById(R.id.resource_list);
        registerForContextMenu(mResourceList);
        mResourceList.setOnItemLongClickListener(onListLongClick);
        mResourceList.setOnItemClickListener(onListClick);
        showList();

        mAddBtn = (LinearLayout) findViewById(R.id.add_footer);
        mAddBtn.setOnClickListener(insertClick);

        // 底部布局
        mLoadingLy = (LinearLayout) findViewById(R.id.main_loading_layout);
        mBottomLy = (LinearLayout) findViewById(R.id.main_bottom_layout);
        // mBottomBtnLy = (LinearLayout) findViewById(R.id.bottom_btn_layout);

        mQuickEditBtn = (ImageButton) findViewById(R.id.quick_edit_btn);
        mQuickEditBtn.setOnClickListener(enterQuickMode);

        mQuitQuickEditBtn = (ImageButton) findViewById(R.id.quit_quick_edit_btn);
        mQuitQuickEditBtn.setOnClickListener(quitQuickMode);

        mRefreshBtn = (ImageButton) findViewById(R.id.btn_refresh);
        mRefreshBtn.setOnClickListener(refreshBtnListern);
        
        mLoadingImage=(ImageView) findViewById(R.id.main_loading_img);
    }
    
    /**
     * 重启Activity事件
     */
    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        updateDataBackground();
    }

    /**
     * 上下文菜单
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.layout.edit_menu, menu);
        menu.setHeaderTitle("编辑");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case R.id.edit_menu_item:
            doEditResource();
            break;
        case R.id.del_menu_item:
            deleteResource(selUrl);
            break;
        }
        return super.onContextItemSelected(item);
    }

    private OnClickListener insertClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            final View view = LayoutInflater.from(ctx).inflate(R.layout.insert_dialog, null);
            Dialog insertDlg = new AlertDialog.Builder(ctx).setTitle("请输入RSS信息").setView(view)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Resource r = new Resource();
                            EditText edit = (EditText) view.findViewById(R.id.name_edit);
                            r.name = edit.getText().toString();
                            edit = (EditText) view.findViewById(R.id.url_edit);
                            r.url = edit.getText().toString();
                            ResourceBusi.insertRes(r);
                            showList();
                            updateDataBackground();
                        }
                    }).setNegativeButton("取消", null).create();
            insertDlg.show();
        }
    };

    /**
     * 进入快速编辑监听器
     * 
     * @author Young
     * 
     */
    private OnClickListener enterQuickMode = new OnClickListener() {
        @Override
        public void onClick(View v) {
            for (int i = 0; i < mCount; i++) {
                TextView textView = (TextView) mResourceList.getChildAt(i).findViewById(
                        R.id.resource_url_text);
                final String urlToDel = textView.getText().toString();
                ImageButton mQuickDelBtn = (ImageButton) mResourceList.getChildAt(i).findViewById(
                        R.id.quick_del_btn);
                mQuickDelBtn.setVisibility(View.VISIBLE);
                mQuickDelBtn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        deleteResource(urlToDel);
                    }
                });

                mQuickEditBtn.setVisibility(View.GONE);
                mQuitQuickEditBtn.setVisibility(View.VISIBLE);
            }
        }
    };

    private OnClickListener quitQuickMode = new OnClickListener() {

        public void onClick(View v) {
            for (int i = 0; i < mCount; i++) {
                ImageButton mQuickDelBtn = (ImageButton) mResourceList.getChildAt(i).findViewById(
                        R.id.quick_del_btn);
                mQuickDelBtn.setVisibility(View.GONE);

            }
            mQuickEditBtn.setVisibility(View.VISIBLE);
            mQuitQuickEditBtn.setVisibility(View.GONE);

        }
    };

    /**
     * 列表项目长按监听
     */
    private OnItemLongClickListener onListLongClick = new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3) {
            // TODO Auto-generated method stub
            TextView nameText = (TextView) view.findViewById(R.id.resource_name_text);
            selName = nameText.getText().toString();
            TextView urlText = (TextView) view.findViewById(R.id.resource_url_text);
            selUrl = urlText.getText().toString();
            mResourceList.showContextMenu();
            return true;
        }

    };

    /**
     * 列表项目单机监听
     */
    private OnItemClickListener onListClick = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
            // TODO Auto-generated method stub
            TextView nameText = (TextView) view.findViewById(R.id.resource_name_text);
            selName = nameText.getText().toString(); // 获取资源名称
            Intent it = new Intent(ctx, RSSFeedRead.class);
            it.putExtra("url", OperResource.getResource(selName).url);
            it.putExtra("name", selName);
            startActivity(it);
        }
    };

    /**
     * 刷新按钮监听
     */
    private OnClickListener refreshBtnListern = new OnClickListener() {
        @Override
        public void onClick(View v) {
            refreshData();
        }
    };

    /**
     * 显示资源
     */
    public void showList() {
        ArrayList<Resource> rList = ResourceBusi.getAllResources();
        ResourceAdapter adpapter = new ResourceAdapter(rList, this);
        ListView list = (ListView) findViewById(R.id.resource_list);
        list.setAdapter(adpapter);
    }

    /**
     * 获取链接数据，改变未读数量，数据注入数据库
     */
    public void updateList() {
        ArrayList<Resource> rList = ResourceBusi.getAllRes();
        mCount = rList.size();
        unreadCount = new int[mCount];
        // 加载网络数据并获取未读数据
        for (int i = 0; i < mCount; i++) {
            MainBusiness.getUrlFeed(rList.get(i).url);
            int count = ResourceBusi.getUnreadCount(rList.get(i).url);
            rList.get(i).unreadCount = count;
            unreadCount[i] = count;
        }
        PubFunction.sendNotify(FINISH_NOTIFIER, handler);
    }

    /**
     * 后台更新
     */
    public void updateDataBackground() {

        // mBottomBtnLy.setVisibility(View.GONE);
        mBottomLy.setVisibility(View.VISIBLE);
//        PubFunction.loadAnimation(mBottomLy, R.anim.fadein);
        PubFunction.loadAnimation(mLoadingImage, R.anim.loading);

        new Thread() {
            public void run() {
                updateList();
            }
        }.start();
    }

    /**
     * 删除资源
     */
    public void deleteResource(String url) {
        ResourceBusi.deleteRes(url);
        showList();
        updateDataBackground();
    }

    /**
     * 修改资源
     */
    public void doEditResource() {
        final View view = LayoutInflater.from(ctx).inflate(R.layout.insert_dialog, null);
        Dialog editDialog = new AlertDialog.Builder(ctx).setTitle("请输入RSS信息").setView(view)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Resource r = new Resource();
                        EditText edit = (EditText) view.findViewById(R.id.name_edit);
                        r.name = edit.getText().toString();
                        edit = (EditText) view.findViewById(R.id.url_edit);
                        r.url = edit.getText().toString();

                        ResourceBusi.editResource(r, selUrl);
                        showList();
                        updateDataBackground();
                    }
                }).setNegativeButton("取消", null).create();
        EditText edit = (EditText) view.findViewById(R.id.name_edit);
        edit.setText(selName);
        edit = (EditText) view.findViewById(R.id.url_edit);
        edit.setText(selUrl);
        editDialog.show();
    }

    /**
     * 更新结束，显示未读数量，加载动画消失
     */
    private void handleUpdateFinish() {
        // 遍历ListView子项
        for (int i = 0; i < mCount; i++) {
            TextView textView = (TextView) mResourceList.getChildAt(i).findViewById(
                    R.id.resource_unreadcount);
            textView.setText(String.valueOf(unreadCount[i]));
            textView.setVisibility(View.VISIBLE);
        }
        
        PubFunction.loadAnimation(mBottomLy,R.anim.fadeout);
        mBottomLy.setVisibility(View.GONE);
        // mBottomBtnLy.setVisibility(View.VISIBLE);
    }

    /**
     * 加载网络数据
     */
    private void refreshData() {
        showList();
        updateDataBackground();
    }

}